# coding: utf-8

from importlib import import_module

from flask import Blueprint


def path(rule, view_func, **kwargs):
    return {"rule": rule, "view_func": view_func, **kwargs}


def include(url_prefix, blueprint_path):
    return {"url_prefix": url_prefix, "blueprint_path": blueprint_path}


def init_blueprint(app):
    blueprint_path_list = app.config.get("INSTALLED_APPS")
    url_path = app.config.get("URL_PATH")
    urlpatterns = import_module(url_path).urlpatterns
    for blueprint_path in blueprint_path_list:
        blueprint_name = blueprint_path.split(".")[-1]
        blueprint = Blueprint(blueprint_name, blueprint_path)
        url_module = import_module("{path}.urls".format(path=blueprint_path))
        try:
            for urls in url_module.urlpatterns:
                blueprint.add_url_rule(**urls)
        except Exception as e:
            print(str(e))
        url_prefix = ""
        for url in urlpatterns:
            if url["blueprint_path"] == blueprint_name + ".urls":
                url_prefix = url["url_prefix"]
                break
        app.register_blueprint(blueprint, url_prefix=url_prefix)
